package cn.icatw.gulimall.auth.controller;

import cn.icatw.common.constant.AuthServerConstant;
import cn.icatw.common.exception.BizCodeEnum;
import cn.icatw.common.utils.R;
import cn.icatw.common.vo.MemberRespVo;
import cn.icatw.gulimall.auth.feign.MemberFeignService;
import cn.icatw.gulimall.auth.feign.ThirdPartyFeignService;
import cn.icatw.gulimall.auth.vo.UserLoginVo;
import cn.icatw.gulimall.auth.vo.UserRegisterVo;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static cn.icatw.common.constant.AuthServerConstant.LOGIN_USER;

/**
 * 登录控制器
 *
 * @author icatw
 * @date 2022/3/21
 * @email 762188827@qq.com
 * @apiNote
 */
@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    ThirdPartyFeignService thirdPartyFeignService;
    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 发送代码
     *
     * @param phone 电话
     * @return {@link R}
     */
    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        //TODO 1、接口防刷
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                //redis缓存验证码，防止同一个phone在60秒内再次发送验证码
                //60秒内不能重复发送
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        //2、验证码的再次校验，存入redis
        String code = UUID.randomUUID().toString().substring(0, 5);
        String substring = code + "_" + System.currentTimeMillis();
        //redis缓存验证码，防止同一个phone在60秒内再次发送验证码
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, substring, 10, TimeUnit.MINUTES);
        thirdPartyFeignService.sendCode(phone, code);
        return R.ok();
    }

    /**
     * 注册
     * redirectAttributes 允许模拟携带属性的重定向
     * //TODO 重定向携带数据，利用session原理
     * //TODO 1、会存在spring session问题
     *
     * @param vo                 签证官
     * @param result             结果
     * @param redirectAttributes 重定向属性
     * @return {@link String}
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/register")
    public String register(@Valid UserRegisterVo vo, BindingResult result, RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().
                    collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            //校验出错，转发到注册页
            //redirectAttributes.addAttribute("errors", errors);
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        String code = vo.getCode();
        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (!StringUtils.isEmpty(s)) {
            if (code.equals(s.split("_")[0])) {
                //删除验证码，令牌机制
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                //验证码比对正确
                //TODO 真正注册，调用远程服务
                R r = memberFeignService.register(vo);
                if (r.getCode() == 0) {
                    //    注册成功
                    return "redirect:http://auth.gulimall.com/login.html";
                } else {
                    //    注册失败
                    HashMap<String, String> errors = new HashMap<>();
                    errors.put("msg", r.getData("msg", new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        //    注册成功，回到首页/登录页
    }

    /**
     * 登录
     *
     * @param vo                 签证官
     * @param redirectAttributes 重定向属性
     * @param session            会话
     * @return {@link String}
     */
    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session) {
        //远程登陆
        R login = memberFeignService.login(vo);
        if (login.getCode() == 0) {
            MemberRespVo data = login.getData("data", new TypeReference<MemberRespVo>() {
            });
            //成功，放入session
            session.setAttribute(LOGIN_USER, data);
            //成功
            return "redirect:http://gulimall.com";
        } else {
            //失败
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", login.getData("msg", new TypeReference<String>() {
            }));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

    /**
     * 登录页面
     * 判断是否已经登陆，若已登录，再次点击登陆页会自动跳转到首页
     *
     * @param session 会话
     * @return {@link String}
     */
    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        Object attribute = session.getAttribute(LOGIN_USER);
        if (attribute == null) {
            //没登录，跳回登陆页
            return "login";
        } else {
            return "redirect:http://gulimall.com";
        }
    }

    /**
     * 注销
     *
     * @param request 请求
     * @return {@link String}
     */
    @GetMapping(value = "/logout.html")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute(LOGIN_USER);
        request.getSession().invalidate();
        return "redirect:http://gulimall.com";
    }
}
